import re

from django.conf import settings
from django.core.mail import send_mail
from rest_framework import serializers
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJS

from celery_tasks.email.tasks import send_email
from users.models import User


class UserSerialziers(serializers.ModelSerializer):
    # 显示指明字段
    password2 = serializers.CharField(max_length=20, min_length=8, write_only=True)
    sms_code = serializers.CharField(max_length=6, min_length=6, write_only=True)
    allow = serializers.CharField(write_only=True)
    token = serializers.CharField(read_only=True)  # 额外添加一个token字段

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'password', 'password2', 'sms_code', 'allow', 'token')
        extra_kwargs = {
            'password': {
                'max_length': 20,
                'min_length': 8,
                'write_only': True,
                'error_messages': {
                    'max_length': '密码过长'
                }
            },
            'username': {
                'max_length': 20,
                'min_length': 5,
                'error_messages': {
                    'max_length': '名字过长'
                }
            },
        }

    # 手机号验证
    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机格式不正确')
        return value

    # 验证选中协议状态
    def validated_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('协议未选中')
        return value

    # 需要对比的数据字段
    def validate(self, attrs):

        #  判断username是否是手机号
        if re.match(r'^1[3-9]\d{9}$', attrs['username']):
            if attrs['username'] != attrs['mobile']:
                raise serializers.ValidationError('用户名和手机号不一致')

        # 密码比对
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('密码不一致')

        # 短信验证码的判断
        # 建立缓存 redis连接
        conn = get_redis_connection('verify')

        # 取出真实验证码  结果是一个：bytes类型的
        real_sms = conn.get('sms_%s' % attrs['mobile'])

        # 判断是否能取出值（是否过期）
        if not real_sms:
            raise serializers.ValidationError('短信验证码已过期')

        # 验证码
        if attrs['sms_code'] != real_sms.decode():
            raise serializers.ValidationError('短信验证码不一致')

        return attrs

    def create(self, validated_data):

        print(validated_data)
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        print(validated_data)

        # 方式一
        # user = super().create(validated_data)

        # # 方式二
        # # 自动加密
        user = User.objects.create_user(username=validated_data['username'], mobile=validated_data['mobile'],
                                        password=validated_data['password'])
        # # 手动加密
        # user = User.objects.create(username=validated_data['username'])
        # user.set_password(validated_data['password'])
        # user.save()

        # 手动生成一个token验证，生成 token数据

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 用户对象额外添加token属性
        user.token = token

        return user


# 用户个人中心的数据
class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'id', 'mobile', 'email', 'email_active')


# 发送邮件
class EmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('email', 'id')

    def update(self, instance, validated_data):
        user = self.context['request'].user
        data = self.context['view'].kwargs
        # 加密用户信息
        tjs = TJS(settings.SECRET_KEY, 300)
        token = tjs.dumps({'id': instance.id}).decode()
        # 构建验证连接
        verify_html = '<a href="http://www.meiduo.site:8080/success_verify_email.html?token=%s">美多商城验证</a>' % token
        # 发送邮件
        # send_mail('biaoti','',settings.EMAIL_FROM,[validated_data['email']],html_message=html)

        send_email.delay(validated_data['email'], verify_html)

        instance.email = validated_data['email']
        instance.save()

        return instance


# 邮箱验证思路拓展
class VerifySerizlizers(serializers.Serializer):
    token = serializers.CharField(write_only=True)

    def validate(self, attrs):

        # 解密验证token
        tjs = TJS(settings.SECRET_KEY, 300)

        try:
            data = tjs.loads(attrs['token'])
        except:
            raise serializers.ValidationError({'errors': '无效token'})

        id = data['id']

        attrs['id'] = id

        return attrs

    def create(self, validated_data):
        # 更新操作
        user = User.objects.get(id=validated_data['id'])
        user.email_active = True
        user.save()

        return user
